package br.fot.granola.oboe.controllers;

import java.util.Hashtable;

import br.fot.granola.oboe.core.Oboe;
import br.fot.granola.oboe.core.Slot;

public class StateMachine {
	private Hashtable< Object, Object > states;
	private Object activeState;
	private Object nextState;
	private Object[] stateParams;
	
	public StateMachine()
	{
		super();
		states = new Hashtable<Object, Object>();
	}
	
	@Slot protected void setState( Object s, Object... params )
	{
		if( this.states.containsKey( s ))
		{
			this.nextState = this.states.get( s );
			this.stateParams = params;
		}
	}
	
	@Slot protected void applyState()
	{
		if( this.nextState == null ) return;
		if( this.activeState == null )
		{
			this.activeState = this.nextState;
			Oboe.addChild( this, this.nextState );
			Oboe.message( this.nextState, "onEnterState", this.stateParams );
		}
		else if( !this.activeState.equals( this.nextState ) )
		{
			Oboe.addChild( this, this.nextState );
			Oboe.messageArray( this.nextState, "onEnterState", this.stateParams );
			Oboe.message( this.activeState, "onExitState");
			Oboe.removeChild( this, this.activeState );
			this.activeState = this.nextState;
		}
	}
	
	@Slot protected void addState( Object k, Object v )
	{
		Object prev = this.states.get(k);
		if( prev != null )
		{
			Oboe.destroy( prev );
		}
		this.states.put( k, v );
	}
}
